#include "Boid.h"
#include "Container.h"
#include "Application.h"
#include <stdlib.h>  

Boid::Boid():mesh(new Mesh()), acceleration(glm::vec3(0, 0, 0)), maxVelocity(100), minVelocity(0){

	int x_bound = Container::get_Instance()->getWidth() - 20;
	int y_bound = Container::get_Instance()->getHeight() - 20;
	int z_bound = Container::get_Instance()->getDepth() - 20;

	position.x = rand() % x_bound - x_bound/2;
	position.y = rand() % y_bound - y_bound/2;
	position.z = rand() % z_bound - z_bound/2;

	velocity.x = rand() % maxVelocity - maxVelocity/2;
	velocity.y = rand() % maxVelocity - maxVelocity/2;
	velocity.z = rand() % maxVelocity - maxVelocity/2;

	//velocity /= glm::vec3(10);

	Application::get_Instance()->updateNumOfBoids();

}

void Boid::draw(){

	glm::vec3 direction = glm::normalize(velocity);
	glm::vec3 up = glm::vec3(0, 1, 0);

	glm::vec3 axis_of_rotation = glm::normalize(glm::cross(up, direction));
	double angle = glm::acos(glm::dot(up, direction)) * 180 / 3.14159265;

	glTranslatef(position.x, position.y, position.z);
	glRotatef(angle, axis_of_rotation.x, axis_of_rotation.y, axis_of_rotation.z);	

	mesh->draw();

	glRotatef(-angle, axis_of_rotation.x, axis_of_rotation.y, axis_of_rotation.z);
	glTranslatef(-position.x, -position.y, -position.z);
	
}

void Boid::collide(){}

void Boid::update(double dt){

	acceleration = Container::get_Instance()->getNormal(position);
	acceleration *= obstacleAvoidanceCoeff;

	glm::vec3 v = velocity;
	velocity += acceleration*glm::vec3(dt);

	if (glm::length(velocity) < minVelocity)
		velocity *= minVelocity/glm::length(v);
	else if (glm::length(velocity) > maxVelocity) 
		velocity *=  maxVelocity/glm::length(v);

	position += velocity*glm::vec3(dt);

}

float Boid::obstacleAvoidanceCoeff = 100.f;